using System.Threading;
using System.Threading.Tasks;
using MediatR;
using B.S.BasicData.EroorCode;
using B.S.BasicData.Domain;
using B.S.BasicData.Infrature;
using System.Linq;
using System.Collections.Generic;
using B.S.BasicData.ApiRead;
using B.S.BasicData.Infrature;
using Microsoft.EntityFrameworkCore;

public class ProindexinfoPagingHandler : IRequestHandler<ProindexinfoPagingRequest, ApiPaging<List<ProindexinfoPagingDto>>>
{
    private readonly AppDbContext _dbContext;
    public ProindexinfoPagingHandler(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<ApiPaging<List<ProindexinfoPagingDto>>> Handle(ProindexinfoPagingRequest request, CancellationToken cancellationToken)
    {
        var query = from p in _dbContext.proindexinfos
                    where !p.IsDeleted
                    join pn in _dbContext.ProductNames on p.ProductNameId equals pn.Id into gj
                    from pn in gj.DefaultIfEmpty()
                    select new ProindexinfoPagingDto
                    {
                        Id = p.Id,
                        ProductNameId = p.ProductNameId,
                        ProductName = pn != null ? pn.Name : string.Empty,
                        BatchNo = p.BatchNo,
                        ShelfLife = p.ShelfLife,
                        LicenseNo = p.LicenseNo,
                        Manufacturer = p.Manufacturer,
                        CoverImage = p.CoverImage,
                        InfoCompleteness = p.InfoCompleteness,
                        IsDeleted = p.IsDeleted,
                        CreatedAt = p.CreatedAt,
                        ModifiedAt = p.ModifiedAt,
                        CreatedBy = p.CreatedBy,
                        ModifiedBy = p.ModifiedBy,
                    };
        int total = await query.CountAsync();
        var data = await query.Skip((request.Page - 1) * request.PageSize).Take(request.PageSize).ToListAsync();
        return ApiPaging<List<ProindexinfoPagingDto>>.Success(data, total, request.Page, request.PageSize);
    }
} 